<?php

/**
 * @category   Ac
 * @package    Application_Model
 * @copyright  Orient Network Ltd
 * @license    Closed
 * @author     John Wilson Lee
 */
class Model_Follow extends Ac_Model
{
	
	const TYPE_PERSONAL = 1;
	const TYPE_BUSINESS = 2;
	
    protected static  $_collection = 'follow';
    //conngroup for user and company models
    protected static $_connectionGroup = 'accounts';
    //db for user and company
    protected static $_db = SHARED_ACCOUNTS_ENV;

    /**
     *
     * @var array define the requirements for this model
     */
    protected static $_requirements = array(
    );

    protected static $_transcript = array(
        '_id'	=> '_id',
        'uid'	=> 'uniqid',
        'us'	=> 'user',
        'us_f'	=> 'user_followed',
        'us_t'	=> 'user_type',
        'c_dt'	=> 'created_at',
   );

    public function __construct($data = array(), $config = array())
	{
        $config['db'] = SHARED_ACCOUNTS_ENV;                
        $config['collection'] = 'follow';
        self::ensureIndex(array('us_f'));
        self::ensureIndex(array('us'));
        self::ensureIndex(array('uid'));
        parent::__construct($data, $config);
    }
    
	public function __isset($name) {
        $val = self::__get($name);
        return!empty($val) ? true : parent::__isset($name);
    }	
    
    public function __get($name)
    {
    	if ($name == 'user_followed') {
            if ($this->type == self::TYPE_PERSONAL) {
                return Model_User::find($this->us_f);
            } else {
                return Model_Company::find($this->us_f);
            }
        } elseif($name == 'user') {
            return Model_User::find($this->us);
        } else {
            return parent::__get($name);
        }
    }
    
    public static function follow($id)
    {
		if (empty($id)) { 
			return false;
		}	
		
		$user = Model_User::find($id);
        if(empty($user)){
            $user = Model_Company::find($id);
        }
        if(empty($user)){
            return false;
        }
        if (!empty($user->cid)) {
            $type = self::TYPE_BUSINESS;
            $user= $user->company;
        } elseif ($user instanceof Model_Company) {
            $type = self::TYPE_BUSINESS;
        } else {
            $type = self::TYPE_PERSONAL;
        }

		$user_id = $user->_id;
		
		if (Zend_Registry::isRegistered('loggedin_user')) {
            $loggedin_user = Zend_Registry::get('loggedin_user')->_id;
            $owner = Model_User::find($loggedin_user);
            if (!empty($owner->cid)) {
	            $loggedin_user = $owner->company->_id;
	        }
            $h = Model_Follow::one(array('user_followed' => $user_id, 'user' => $loggedin_user));
        } else {
            //generate a unique id and put it in a cookie if it doesn 't exists
            if (empty($_COOKIE['ac_bookmark'])) {
                $uniqid = uniqid('', true);
                setcookie('ac_bookmark', $uniqid, time()+86400*365, "/");
                $_COOKIE['ac_bookmark'] = $uniqid;
            } else {
                $uniqid = $_COOKIE['ac_bookmark'];
            }
            $h = Model_Follow::one(array('user_followed' => $user_id, 'uid' => $uniqid));
        }

        $count = (int)self::getCountFollowers($user_id);

        if (empty($h)) {
            $h                  = new self;
            $h->user_type       = $type;
            $h->user_followed   = $user_id;
            if (!empty($loggedin_user)) {
                $h->user   = $loggedin_user;
            } else {
                $h->uniqid = $uniqid;
            }
            $h->created_at = new MongoDate(time());
            $h->save();
            if (!empty($user)) {
                $user->count_followers = intval($count) + 1;
                $user->save();
            }
            if (!empty($loggedin_user)) {
            	$user = Model_User::find($loggedin_user);
            	if(empty($owner->cid)){
		            $user = Model_Company::find($loggedin_user);
		        }
                //$user = Model_User::find($loggedin_user);
                //if (!empty($user)) {
                    $user->count_following = intval($user->count_following) + 1;
                    $user->save();
                //}
            }
		}

        //echo '<pre>';print_r($user);exit;

        $count = (int)self::getCountFollowers($user_id);
        return $count;
	}
	
	public static function isFollowing($id)
	{
		if(empty($id))
		{ 
			return false;
		}	
	
        $user = Model_User::find($id);
        if(empty($user)){
            $user = Model_Company::find($id);
        }
        if(empty($user)){
            return false;
        }

        if (!empty($user->cid)) {
            $type = self::TYPE_BUSINESS;
            $user= $user->company;
        } elseif ($user instanceof Model_Company) {
            $type = self::TYPE_BUSINESS;
        } else {
            $type = self::TYPE_PERSONAL;
        }
        $user_id = $user->_id; 
    	
		if (Zend_Registry::isRegistered('loggedin_user')) {
            $follower = Zend_Registry::get('loggedin_user')->_id;
            $h = Model_Follow::one(array('user_followed' => $user_id, 'user' => $follower));
        } else {
            //generate a unique id and put it in a cookie if it doesn 't exists
            if (empty($_COOKIE['ac_bookmark'])) {
                $uniqid = uniqid('', true);
                setcookie('ac_bookmark', $uniqid, time()+86400*365, '/');
                $_COOKIE['ac_bookmark'] = $uniqid;
            } else {
                $uniqid = $_COOKIE['ac_bookmark'];
            }
            $h = Model_Follow::one(array('user_followed' => $user_id, 'uid' => $uniqid));
        }
        /*
        if ($user_id == '4f1664e4e62d6cd92d30a1bf') {
            echo '<pre>';var_dump($user, $uniqid, $h);exit;
        }
        */
        
        if (empty($h)) {
            return false;
        } else {
			return true;
		}
	}
	
	public static function unfollow($id)
	{
		if(empty($id)){ 
			return false;
		}	

        $user = Model_User::find($id);
        if(empty($user)){
            $user = Model_Company::find($id);
        }
        if(empty($user)){
            return false;
        }
        if (!empty($user->cid)) {
            $type = self::TYPE_BUSINESS;
            $user= $user->company;
        } elseif ($user instanceof Model_Company) {
            $type = self::TYPE_BUSINESS;
        } else {
            $type = self::TYPE_PERSONAL;
        }


        $user_id = $user->_id;


		if (Zend_Registry::isRegistered('loggedin_user')) {
            $loggedin_user = Zend_Registry::get('loggedin_user')->_id;
            $h = Model_Follow::remove(array('us_f' => $user_id, 'us' => $loggedin_user));
            $count = (int)self::getCountFollowers($user_id);
            if (!empty($user)) {
                $user->count_followers = intval($count) - 1;
                $user->save();
            }
            if (!empty($loggedin_user)) {
                $user = Model_User::find(loggedin_user);
                if (!empty($user)) {
                    $user->count_following = intval($user->count_following) - 1;
                    $user->save();
                }
            }

            return $count;
        } else {
            //generate a unique id and put it in a cookie if it doesn 't exists
            if (empty($_COOKIE['ac_bookmark'])) {
                $uniqid = uniqid('', true);
                setcookie('ac_bookmark', $uniqid, time()+86400*365, "/");
                $_COOKIE['ac_bookmark'] = $uniqid;
            } else {
                $uniqid = $_COOKIE['ac_bookmark'];
            }
            $h = Model_Follow::remove(array('us_f' => $user_id, 'uid'=> $uniqid));
            $count = (int)self::getCountFollowers($user_id);
            if (!empty($user)) {
                $user->count_followers = intval($count) - 1;
                $user->save();
            }
            if (!empty($loggedin_user)) {
                $user = Model_User::find(loggedin_user);
                if (!empty($user)) {
                    $user->count_following = intval($user->count_following) - 1;
                    $user->save();
                }
            }

            $count = (int)self::getCountFollowers($user_id);
            return $count;
        }
        return false;
	}

    public static function getCountFollowing($id) {

        $user = Model_User::find($id);
        if(empty($user)){
            $user = Model_Company::find($id);
        }
        if(empty($user)){
            return false;
        }
        if (!empty($user->cid)) {
            $user= $user->company;
        }        

        /*if (!empty($user) && !empty($user->count_following)) {
            return $user->count_following;
        }*/

        $res = self::all(array('us' => $user->_id))->count();
        //update counter if we have to
        if (!empty($user)) {
            if($user->count_following != $res) {
                $user->count_following = $res;
                $user->save();
            }
        }

        return $res > 0 ? $res : '';
    }

    public static function getCountFollowers($id) {

        $user = Model_User::find($id);
        if(empty($user)){
            $user = Model_Company::find($id);
        }
        if(empty($user)){
            return false;
        }
        if (!empty($user->cid)) {
            $user= $user->company;
        }        

        /*if (!empty($user) && !empty($user->count_followers)) {
            return $user->count_followers;
        }*/

        $res = self::all(array('us_f' => $user->_id))->count();
        //update counter if we have to
        if (!empty($user)) {
            if ($user->count_followers != $res) {
                $user->count_followers = $res;
                $user->save();
            }
        }

        return $res > 0 ? $res : '';
    }
   
    public static function getFollowers($id)
    {
        $user = Model_User::find($id);
        if(empty($user)){
            $user = Model_Company::find($id);
        }
        if(empty($user)){
            return false;
        }
        if (!empty($user->cid)) {
            $user = $user->company;
        }
        
        return Model_Follow::all(array('us_f' => $user->_id));   
    }

    public static function getFollowing($id)
    {
        $user = Model_User::find($id);
        if(empty($user)){
            $user = Model_Company::find($id);
        }
        if(empty($user)){
            return false;
        }
        if (!empty($user->cid)) {
            $user = $user->company;
        }

        return Model_Follow::all(array('user' => $user->_id));
    }
    
    
}
